package com.wh.message.mongo.util;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;


/**
 * 工具类
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.mongo.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class MongoUtil {

    private static Logger logger = LoggerFactory.getLogger(MongoUtil.class);

    /**
     * 属性配置文件
     */
    private final static String propertieName = "properties/system";

    /**
     * 读取MongoDB连接池基本配置信息
     */
    private final static String connectionsPerHost = ResourceBundle.getBundle(propertieName).getString("mongo.connectionsPerHost");
    private final static String threadsAllowedToBlockForConnectionMultiplier = ResourceBundle.getBundle(propertieName).getString("mongo.threadsAllowedToBlockForConnectionMultiplier");
    private final static String selectionTimeout = ResourceBundle.getBundle(propertieName).getString("mongo.selectionTimeout");
    private final static String socketTimeout = ResourceBundle.getBundle(propertieName).getString("mongo.socketTimeout");
    private final static String connectTimeout = ResourceBundle.getBundle(propertieName).getString("mongo.connectTimeout");
    private final static String maxWaitTime = ResourceBundle.getBundle(propertieName).getString("mongo.maxWaitTime");
    private final static String socketKeepAlive = ResourceBundle.getBundle(propertieName).getString("mongo.socketKeepAlive");

    /**
     * 存放mongoDatabase集合
     */
    public static Map<String, MongoDatabase> mongoDatabaseMap = new HashMap<>();

    /**
     * 初始化MongoDB
     * @param database 数据库名称
     * @return
     */
    public static MongoDatabase initDb(String database) {
        MongoDatabase mongoDatabase = mongoDatabaseMap.get(database);
        if (null != mongoDatabase) {
            //当已经存在时直接返回对应的数据连接对象
            return mongoDatabase;
        }
        try {
            //连接主机
            final String hostName = ResourceBundle.getBundle(propertieName).getString("mongo." + database + ".host");
            //链接主机端口
            final String port = ResourceBundle.getBundle(propertieName).getString("mongo." + database + ".port");
            //链接主机用户名
            final String userName = ResourceBundle.getBundle(propertieName).getString("mongo." + database + ".username");
            //链接主机密码
            final String password = ResourceBundle.getBundle(propertieName).getString("mongo." + database + ".password");

            //构建ServerAddress
            ServerAddress serverAddress = new ServerAddress(hostName, Integer.parseInt(port));
            //构建MongoCredential
            MongoCredential mongoCredential = MongoCredential.createCredential(userName, database, password.toCharArray());
            //构建mongoClientOptions
            MongoClientOptions mongoClientOptions = MongoClientOptions.builder()
                    .serverSelectionTimeout(Integer.valueOf(selectionTimeout))
                    .socketTimeout(Integer.valueOf(socketTimeout))
                    .maxWaitTime(Integer.valueOf(maxWaitTime))
                    .socketKeepAlive(Boolean.valueOf(socketKeepAlive))
                    .connectionsPerHost(Integer.valueOf(connectionsPerHost))
                    .threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(threadsAllowedToBlockForConnectionMultiplier))
                    .connectTimeout(Integer.valueOf(connectTimeout))
                    .build();
            //创建MongoClient
            MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential), mongoClientOptions);
            //获取mongoDatabase
            mongoDatabase = mongoClient.getDatabase(database);
            //存放集合
            mongoDatabaseMap.put(database, mongoDatabase);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("创建MongoDB数据库链接异常 " + e.getMessage());
        }
            return mongoDatabase;
    }
}
